package com.ingenico.insider.services.impl;

import java.util.MissingResourceException;
import java.util.logging.Logger;

import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.JRadioButtonMenuItem;

import com.ingenico.insider.awt.event.ThemeActionListener;

import net.infonode.docking.theme.DockingWindowsTheme;

public final class ThemesMenuSupplier {
	private static final Logger _logger = Logger.getLogger(ThemesMenuSupplier.class.getCanonicalName());

	/**
	 * Public constant keywords
	 */
	public static final String THEMES_KEY = "themes";

	/**
	 * singleton instance
	 */
	private static ThemesMenuSupplier instance;

	/**
	 * retrieve the singleton instance
	 *
	 * @return the ThemesMenuSupplier singleton
	 */
	public static ThemesMenuSupplier getInstance() {
		if (instance == null) {
			_logger.info(ThemesMenuSupplier.class.getName() + " instance does not exist... Creating instance.");
			instance = new ThemesMenuSupplier();
		}
		return instance;
	}

	/**
	 * The themes menu that the one and only instance of ThemesMenuSupplier manages
	 */
	private final JMenu themesMenu;

	/**
	 * private constructor of final class to prevent external instantiation
	 */
	private ThemesMenuSupplier() {
		themesMenu = getThemesMenu();
		_logger.finer("themes menu = " + themesMenu);

		_logger.fine("Initializing themes menu.");
		initThemesMenu();

		_logger.fine("Registering themes menu under the display menu.");
		StandardMenuSupplier.getInstance().getDisplayMenu().add(themesMenu);
	};

	/**
	 * Initializes the themes menu with a list of themes provided by the IDWThemesSupplier
	 * 
	 * created JMenuItems are automatically associated with the theme menu listener and added
	 * to the themes JMenu
	 */
	private void initThemesMenu() {
		final ButtonGroup group = new ButtonGroup();
		final ThemeActionListener al = new ThemeActionListener();
		final DockingWindowsTheme[] availableThemes = IDWThemesSupplier.getInstance().getAvailableThemes();
		final DockingWindowsTheme selectedTheme = DockableViewsSupplier.getInstance().getTheme();

		JRadioButtonMenuItem item;
		DockingWindowsTheme theme;
		for (int i = 0; i < availableThemes.length; i++) {
			theme = availableThemes[i];

			item = new JRadioButtonMenuItem(theme.getName());
			item.setActionCommand(Integer.toString(i));
			item.setSelected(theme == selectedTheme);
			item.addActionListener(al);

			_logger.fine("Adding new theme : \"" + theme + "\".");
			group.add(item);

			themesMenu.add(item);
		}
	}

	/**
	 * Convenience method that returns the themes menu
	 * 
	 * @return the themes menu
	 */
	public JMenu getThemesMenu () throws MissingResourceException {
		return StandardMenuSupplier.getInstance().getStandardMenu(THEMES_KEY);
	}
}
